package WeekEleven;

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestUnSynchronizedThread2015082 {

	/**
	 * @param args
	 * @throws InterruptedException
	 */
	//201521123082
	public static void main(String[] args) throws InterruptedException {
		// TODO AArrayList<E>acted method stub
	int n=3;
	ArrayList<Callable<Object>> tasks =new ArrayList<>();
	ExecutorService exec= Executors.newCachedThreadPool();
	for(int i=0;i<n;i++){
		tasks.add(Executors.callable(new Adder()));
	}
	for(int i=0;i<n;i++){
		tasks.add(Executors.callable(new Subtracter()));
	}
	exec.invokeAll(tasks);
	System.out.println(Counter.getId());
	System.out.println("main end");
	}

}

class Adder implements Runnable {

	@Override
	public void run() {
		for (int i = 0; i < 10000; i++)
			Counter.addId();
		System.out.println(Thread.currentThread().getName() + " end");
	}
}

class Subtracter implements Runnable {

	@Override
	public void run() {
		for (int i = 0; i < 10000; i++)
			Counter.subtractId();
		System.out.println(Thread.currentThread().getName() + " end");
	}
}
//201521123082
class Counter {
	private static int id = 0;

	public synchronized static void addId() {
		id++;
	}

	public synchronized static void subtractId() {
		id--;
	}

	public static int getId() {
		return id;
	}
}
